package org.dftproject.genesis.core.tasks;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;


public class TaskManager {

	private static final TaskManager singleton = new TaskManager();
	
	private final List<ITaskManagerListener> listeners = Collections.synchronizedList(new LinkedList<ITaskManagerListener>());
	
	private final ITaskRepository repository = new VolatileTaskRepository();

	private TaskManager() {
	}

	/**
	 * Returns the singleton task manager instance.
	 * @return the task manager
	 */
	public static TaskManager getDefault() {
		return singleton;
	}

	public ITask[] getTasks() {
		return repository.getTasks().toArray(new ITask[0]);
	}
	
	public ITask getTask(String id) {
		return repository.getTask(id);
	}
	
	public void addTask(ITask task) {
		repository.addTask(task);
		notifyTaskAdded(task);
	}
	
	public void updateTask(ITask task) {
		repository.updateTask(task);
		notifyTaskUpdated(task);
	}

	public void removeTask(ITask task) {
		repository.removeTask(task);
		notifyTaskRemoved(task);
	}
	
	public void addListener(ITaskManagerListener listener) {
		listeners.add(listener);
	}

	public void removeListener(ITaskManagerListener listener) {
		listeners.remove(listener);
	}

	protected void notifyTaskAdded(ITask task) {
		for (ITaskManagerListener listener : listeners)
			listener.taskAdded(task);
	}
	
	protected void notifyTaskUpdated(ITask task) {
		for (ITaskManagerListener listener : listeners)
			listener.taskUpdated(task);
	}

	protected void notifyTaskRemoved(ITask task) {
		for (ITaskManagerListener listener : listeners)
			listener.taskRemoved(task);
	}

}
